<template>
  <div class="login">
    <info :ruleForm="contextInfo" @on-behavior="onLogin" ref="infoRef" />
  </div>
</template>

<script lang="ts">
import { reactive, ref, defineComponent } from "vue";
import info, { ContextProps } from "../components/ReInfo/index.vue";
// import { login } from "/@/api/user";
import { useRouter, useRoute } from "vue-router";
import { storageLocal } from "/@/utils/storage";
// import { errorMessage, successMessage } from "/@/utils/message";
import NotifMessage from "/@/utils/message/notification";
import axios from "axios";
import qs from "qs";
import JSEncrypt from "jsencrypt";
import { deptSync } from "/@/api/home";
export default defineComponent({
  name: "login",
  components: {
    info
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const infoRef = ref<HTMLElement | null>(null) as any;

    const baseUrl = ref(import.meta.env.VITE_BASE_URL);

    const contextInfo: ContextProps = reactive({
      userName: "",
      passWord: "",
      identify: ""
    });

    const toPage = (info: Object): void => {
      storageLocal.setItem("info", info);
      const { redirect } = route.query;
      getDeptSync();
      if (redirect) {
        window.location.href = `${redirect}`;
      } else {
        router.replace({ path: "/" });
      }
    };

    const getDeptSync = async () => {
      await deptSync({});
    };

    // 登录
    const onLogin = async () => {
      const encryptor = new JSEncrypt(); // 创建加密对象实例
      let publickKey = `MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKcbECgXDZ/989X8TuAFfQpDUi0i5n7EZpwGvbETXLXtHunS1SPDbLlrlYjSaF9bAAdf5SsPtkOyoQJALMw24AkCAwEAAQ==`;

      // 生产环境的密钥
      if (import.meta.env.VITE_PROJECT_ENV === "pre") {
        publickKey = `MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOoQrxqdDPj7Yafbp+qDnv4XZ+3J9wP7DTT3Lu1vwOsq
      cMW4x5lo54ROu7VMx1m4iaUxj7L/uApoh2klC4muEx8CAwEAAQ==`;
      }
      const publicPassword = `-----BEGIN PUBLIC KEY-----${publickKey}-----END PUBLIC KEY-----`;
      encryptor.setPublicKey(publicPassword); //设置公钥
      let { userName, passWord } = contextInfo;

      const rsaPassWord = encryptor.encrypt(passWord); // 对内容进行加密
      const transferPassword = btoa(rsaPassWord as string);
      // console.log(rsaPassWord, transferPassword, "rsaPassWord");
      const params = {
        userName,
        password: transferPassword
      };
      const loginUrl = `${baseUrl.value}/snow-admin/login?${qs.stringify(
        params
      )}`;
      try {
        const res = await axios.post(loginUrl);
        if (res.status === 200) {
          // successMessage(`${res.data.body.message}`);
          NotifMessage.success(res.data.body.message);
          // console.log(res);
          toPage({
            username: res.data.body.data.userName,
            name: res.data.body.data.name,
            userId: res.data.body.data.userId,
            accessToken: res.data.body.data.token
          });
        }
      } catch (err) {
        // 如果错误就刷新验证码
        infoRef.value.refreshCode();
        if (err?.response?.status === 401) {
          NotifMessage.error("用户名或者密码错误");
          // errorMessage("用户名或者密码错误");
        }
        console.log(err);
      }
    };

    return {
      infoRef,
      contextInfo,
      onLogin,
      // router,
      toPage
    };
  }
});
</script>
